using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp;
using BW.WMS.OperationKanban.WCL.Dto.Input;
using BW.WMS.OperationKanban.WCL.Dto.Output;
using BW.WMS.Model;
using BW.WMS.CodeEnum;

namespace BW.WMS.OperationKanban.WCL
{
    /// <summary>
    /// 货品管理服务实现
    /// </summary>
    public class GoodsManagementAppService : ApplicationService, IGoodsManagementAppService
    {
        private readonly IRepository<Dm_Item, Guid> _itemRepository;
        private readonly IRepository<Dm_ItemType, Guid> _itemTypeRepository;
        private readonly IRepository<Dm_Unit, Guid> _unitRepository;
        private readonly IRepository<Dm_Warehouser, Guid> _warehouseRepository;
        private readonly IRepository<Dm_Librarylocation, Guid> _locationRepository;
        public GoodsManagementAppService(
            IRepository<Dm_Item, Guid> itemRepository,
            IRepository<Dm_ItemType, Guid> itemTypeRepository,
            IRepository<Dm_Unit, Guid> unitRepository,
            IRepository<Dm_Warehouser, Guid> warehouseRepository,
            IRepository<Dm_Librarylocation, Guid> locationRepository)
        {
            _itemRepository = itemRepository;
            _itemTypeRepository = itemTypeRepository;
            _unitRepository = unitRepository;
            _warehouseRepository = warehouseRepository;
            _locationRepository = locationRepository;
        }
        /// <summary>
        /// 获取货品列表
        /// </summary>
        public async Task<List<GoodsOutput>> GetGoodsListAsync(GoodsQueryInput input)
        {
            try
            {
                // 获取基础查询
                var queryable = await _itemRepository.GetQueryableAsync();              
                // 构建LINQ查询，排除ExtraProperties有问题的记录
                var query = queryable.Where(x => !string.IsNullOrEmpty(x.Itemid));
                // 应用搜索条件
                if (!string.IsNullOrEmpty(input.GoodsNameOrCode))
                {
                    query = query.Where(x => x.Itemname.Contains(input.GoodsNameOrCode) || 
                                            x.Itemid.Contains(input.GoodsNameOrCode));
                }
                if (!string.IsNullOrEmpty(input.ItemTypeId))
                {
                    query = query.Where(x => x.Itemtypeid == input.ItemTypeId);
                }
                if (!string.IsNullOrEmpty(input.UnitId))
                {
                    query = query.Where(x => x.Unitid == input.UnitId);
                }
                if (input.Status.HasValue)
                {
                    query = query.Where(x => x.Satus == input.Status.Value);
                }
                if (!string.IsNullOrEmpty(input.ItemSpec))
                {
                    query = query.Where(x => x.Itemspec.Contains(input.ItemSpec));
                }
                // 分步获取数据，避免ExtraProperties解析错误
                var items = new List<Dm_Item>();
                try
                {
                    // 先获取ID列表
                    var itemIds = await query.Select(x => x.Id).ToListAsync();
                    
                    // 逐个获取完整记录，跳过有问题的记录
                    foreach (var id in itemIds)
                    {
                        try
                        {
                            var item = await _itemRepository.GetAsync(id);
                            if (item != null)
                            {
                                items.Add(item);
                            }
                        }
                        catch
                        {
                            // 跳过有问题的记录
                            continue;
                        }
                    }
                }
                catch
                {
                    // 如果批量查询失败，返回空列表
                    return new List<GoodsOutput>();
                }
                if (items.Count == 0)
                {
                    return new List<GoodsOutput>();
                }
                // 使用LINQ查询获取货品类型和单位信息
                var itemTypeIds = items.Where(x => !string.IsNullOrEmpty(x.Itemtypeid))
                                     .Select(x => x.Itemtypeid)
                                     .Distinct()
                                     .ToList();
                var unitIds = items.Where(x => !string.IsNullOrEmpty(x.Unitid))
                                 .Select(x => x.Unitid)
                                 .Distinct()
                                 .ToList();
                // 批量查询货品类型和单位信息
                var itemTypes = new Dictionary<string, string>();
                var units = new Dictionary<string, string>();
                try
                {
                    var itemTypeQueryable = await _itemTypeRepository.GetQueryableAsync();
                    var itemTypeList = await itemTypeQueryable
                        .Where(x => itemTypeIds.Contains(x.Itemtypeid))
                        .ToListAsync();
                    itemTypes = itemTypeList.ToDictionary(x => x.Itemtypeid, x => x.Itemtypename);

                    var unitQueryable = await _unitRepository.GetQueryableAsync();
                    var unitList = await unitQueryable
                        .Where(x => unitIds.Contains(x.Unitid))
                        .ToListAsync();
                    units = unitList.ToDictionary(x => x.Unitid, x => x.Unitname);
                }
                catch
                {
                    // 如果关联查询失败，使用空字典
                }
                // 使用LINQ查询转换为DTO
                var goodsOutputs = items.Select(item =>
                {
                    try
                    {
                        var goodsOutput = ObjectMapper.Map<Dm_Item, GoodsOutput>(item);
                        // 设置关联信息
                        goodsOutput.ItemTypeName = !string.IsNullOrEmpty(item.Itemtypeid) && itemTypes.ContainsKey(item.Itemtypeid) 
                            ? itemTypes[item.Itemtypeid] 
                            : "未知类型";
                        
                        goodsOutput.UnitName = !string.IsNullOrEmpty(item.Unitid) && units.ContainsKey(item.Unitid) 
                            ? units[item.Unitid] 
                            : "未知单位";
                        
                        // 设置模拟数据
                        goodsOutput.WarehouseName = "主仓库";
                        goodsOutput.LocationName = "A区-01-01";
                        goodsOutput.Barcode = $"BAR{item.Itemid}";
                        goodsOutput.CurrentInventory = 100;
                        goodsOutput.InventoryAmount = goodsOutput.CurrentInventory * item.Purchaseprice;
                        goodsOutput.InboundQuantity = 150;
                        goodsOutput.OutboundQuantity = 50;                      
                        return goodsOutput;
                    }
                    catch
                    {
                        return null;
                    }
                })
                .Where(x => x != null)
                .ToList();
                return goodsOutputs;
            }
            catch
            {
                return new List<GoodsOutput>();
            }
        }
        /// <summary>
        /// 获取库存汇总信息
        /// </summary>
        public async Task<InventorySummaryOutput> GetInventorySummaryAsync()
        {
            try
            {
                // 使用LINQ查询获取货品数据
                var queryable = await _itemRepository.GetQueryableAsync();
                
                // 使用LINQ聚合函数计算汇总数据，添加异常处理
                var summaryData = await queryable
                    .Where(x => !string.IsNullOrEmpty(x.Itemid))
                    .Select(x => new
                    {
                        ItemCount = 1,
                        CurrentInventory = 100,
                        InventoryAmount = x.Purchaseprice * 100,
                        InboundQuantity = 150,
                        OutboundQuantity = 50
                    })
                    .GroupBy(x => 1)
                    .Select(g => new
                    {
                        TotalItems = g.Count(),
                        TotalCurrentInventory = g.Sum(x => x.CurrentInventory),
                        TotalInventoryAmount = g.Sum(x => x.InventoryAmount),
                        TotalInboundQuantity = g.Sum(x => x.InboundQuantity),
                        TotalOutboundQuantity = g.Sum(x => x.OutboundQuantity)
                    })
                    .FirstOrDefaultAsync();               
                return new InventorySummaryOutput
                {
                    CurrentInventoryQuantity = summaryData?.TotalCurrentInventory ?? 0,
                    CurrentInventoryAmount = summaryData?.TotalInventoryAmount ?? 0,
                    InboundQuantity = summaryData?.TotalInboundQuantity ?? 0,
                    OutboundQuantity = summaryData?.TotalOutboundQuantity ?? 0
                };
            }
            catch (Exception ex)
            {
                // 如果查询失败，返回默认值
                return new InventorySummaryOutput
                {
                    CurrentInventoryQuantity = 0,
                    CurrentInventoryAmount = 0,
                    InboundQuantity = 0,
                    OutboundQuantity = 0
                };
            }
        }
        /// <summary>
        /// 获取仓库列表
        /// </summary>
        public async Task<ListResultDto<WarehouseDto>> GetWarehousesAsync()
        {
            try
            {
                var queryable = await _warehouseRepository.GetQueryableAsync();
                var warehouses = await queryable.ToListAsync(); // 移除Status限制              
                var warehouseDtos = warehouses.Select(x => new WarehouseDto
                {
                    Id = x.Id,
                    WarehouseId = x.Warehouseid,
                    WarehouseName = x.Warehousename,
                    Status = x.Status
                }).ToList();
                
                return new ListResultDto<WarehouseDto>
                {
                    Items = warehouseDtos
                };
            }
            catch (Exception ex)
            {
                return new ListResultDto<WarehouseDto>
                {
                    Items = new List<WarehouseDto>()
                };
            }
        }
        /// <summary>
        /// 获取库位列表
        /// </summary>
        public async Task<ListResultDto<LocationDto>> GetLocationsAsync(string warehouseId = null)
        {
            try
            {
                var queryable = await _locationRepository.GetQueryableAsync();                
                // 构建LINQ查询
                var query = queryable.Where(x => !string.IsNullOrEmpty(x.Librarylocationid));              
                // 如果指定了仓库ID，则过滤库位
                if (!string.IsNullOrEmpty(warehouseId))
                {
                    query = query.Where(x => x.Warehouseid == warehouseId);
                }              
                // 获取库位数据
                var locations = await query.ToListAsync();                
                // 使用LINQ转换为DTO
                var locationDtos = locations.Select(x => new LocationDto
                {
                    Id = x.Id,
                    LocationId = x.Librarylocationid,
                    LocationName = x.Librarylocationname,
                    WarehouseId = x.Warehouseid,
                    Status = x.Status
                }).ToList();                
                return new ListResultDto<LocationDto>
                {
                    Items = locationDtos
                };
            }
            catch
            {
                return new ListResultDto<LocationDto>
                {
                    Items = new List<LocationDto>()
                };
            }
        }
        /// <summary>
        /// 获取库位下拉框数据
        /// </summary>
        public async Task<List<LocationSelectDto>> GetLocationSelectListAsync(string warehouseId = null)
        {
            try
            {
                var queryable = await _locationRepository.GetQueryableAsync();
                
                // 构建LINQ查询
                var query = queryable.Where(x => !string.IsNullOrEmpty(x.Librarylocationid));
                
                // 如果指定了仓库ID，则过滤库位
                if (!string.IsNullOrEmpty(warehouseId))
                {
                    query = query.Where(x => x.Warehouseid == warehouseId);
                }              
                // 获取库位数据
                var locations = await query.ToListAsync();
                // 使用LINQ转换为下拉框DTO
                var locationSelectDtos = locations.Select(x => new LocationSelectDto
                {
                    Value = x.Librarylocationid,
                    Label = x.Librarylocationname,
                    WarehouseId = x.Warehouseid
                }).ToList();
                return locationSelectDtos;
            }
            catch
            {
                return new List<LocationSelectDto>();
            }
        }
        /// <summary>
        /// 刷新数据
        /// </summary>
        public async Task<bool> RefreshDataAsync()
        {
            try
            {
                // 这里可以添加缓存刷新、数据同步等逻辑
                // 暂时返回成功
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 导出货品数据
        /// </summary>
        public async Task<byte[]> ExportGoodsDataAsync(GoodsQueryInput input)
        {
            // 获取所有数据（不分页）
            input.MaxResultCount = int.MaxValue;
            input.SkipCount = 0;
            var result = await GetGoodsListAsync(input);

            // 这里应该实现Excel导出逻辑
            // 暂时返回空数组，实际项目中可以使用EPPlus或NPOI等库
            return new byte[0];
        }

        /// <summary>
        /// 获取货品类型列表
        /// </summary>
        public async Task<ListResultDto<ItemTypeDto>> GetItemTypesAsync()
        {
            try
            {
                var queryable = await _itemTypeRepository.GetQueryableAsync();
                
                // 先查询所有数据，不限制Status
                var allItemTypes = await queryable.ToListAsync();
                
                // 如果所有数据都为空，尝试查询Status不为0的数据
                if (!allItemTypes.Any())
                {
                    // 查询所有Status的数据
                    var itemTypes = await queryable.ToListAsync();
                    
                    var itemTypeDtos = itemTypes.Select(x => new ItemTypeDto
                    {
                        Id = x.Id,
                        ItemTypeId = x.Itemtypeid,
                        ItemTypeName = x.Itemtypename,
                        Status = x.Status
                    }).ToList();
                    
                    return new ListResultDto<ItemTypeDto>
                    {
                        Items = itemTypeDtos
                    };
                }
                else
                {
                    // 使用所有数据
                    var itemTypeDtos = allItemTypes.Select(x => new ItemTypeDto
                    {
                        Id = x.Id,
                        ItemTypeId = x.Itemtypeid,
                        ItemTypeName = x.Itemtypename,
                        Status = x.Status
                    }).ToList();
                    return new ListResultDto<ItemTypeDto>
                    {
                        Items = itemTypeDtos
                    };
                }
            }
            catch (Exception ex)
            {
                // 返回空列表
                return new ListResultDto<ItemTypeDto>
                {
                    Items = new List<ItemTypeDto>()
                };
            }
        }
        /// <summary>
        /// 获取单位列表
        /// </summary>
        public async Task<ApiPaging<UnitDto>> GetUnitsAsync()
        {
            try
            {
                Console.WriteLine("=== 开始查询单位数据 ===");
                
                // 1. 获取IQueryable
                var queryable = await _unitRepository.GetQueryableAsync();
                Console.WriteLine($"获取到IQueryable，类型: {queryable.GetType().Name}");
                
                // 2. 检查查询是否为空
                var count = await queryable.CountAsync();
                Console.WriteLine($"查询到的总记录数: {count}");
                
                if (count == 0)
                {
                    Console.WriteLine("没有查询到任何记录，可能的原因:");
                    Console.WriteLine("1. 数据库表为空");
                    Console.WriteLine("2. 表名映射错误");
                    Console.WriteLine("3. 数据库连接问题");
                    return new ApiPaging<UnitDto>
                    {
                        PageData = new List<UnitDto>()
                    };
                }            
                // 5. 转换为DTO
                var unitDtos =from a in queryable
                              select new UnitDto
                              {
                                  UnitId = a.Unitid,
                                  UnitName = a.Unitname,
                                  Status = a.Status
                              };
                return new ApiPaging<UnitDto>
                {
                    PageData = unitDtos.ToList()
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取单位列表异常: {ex.Message}");
                Console.WriteLine($"异常类型: {ex.GetType().Name}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return new ApiPaging<UnitDto>
                {
                    PageData = new List<UnitDto>()
                };
            }
        }
        /// <summary>
        /// 测试数据库连接和表名
        /// </summary>
        public async Task<string> TestDatabaseConnectionAsync()
        {
            try
            {
                Console.WriteLine("=== 开始数据库连接测试 ===");
                // 测试单位表
                Console.WriteLine("1. 测试单位表 (Dm_Unit)...");
                var unitQueryable = await _unitRepository.GetQueryableAsync();
                var unitCount = await unitQueryable.CountAsync();
                Console.WriteLine($"   单位表记录数: {unitCount}");
                
                if (unitCount > 0)
                {
                    var sampleUnit = await unitQueryable.FirstOrDefaultAsync();
                    Console.WriteLine($"   样本单位: {sampleUnit?.Unitname} (ID: {sampleUnit?.Id})");
                }
                
                // 测试货品类型表
                Console.WriteLine("2. 测试货品类型表 (Dm_ItemType)...");
                var itemTypeQueryable = await _itemTypeRepository.GetQueryableAsync();
                var itemTypeCount = await itemTypeQueryable.CountAsync();
                Console.WriteLine($"   货品类型表记录数: {itemTypeCount}");              
                if (itemTypeCount > 0)
                {
                    var sampleItemType = await itemTypeQueryable.FirstOrDefaultAsync();
                    Console.WriteLine($"   样本货品类型: {sampleItemType?.Itemtypename} (ID: {sampleItemType?.Id})");
                }                
                // 测试仓库表
                Console.WriteLine("3. 测试仓库表 (Dm_Warehouser)...");
                var warehouseQueryable = await _warehouseRepository.GetQueryableAsync();
                var warehouseCount = await warehouseQueryable.CountAsync();
                Console.WriteLine($"   仓库表记录数: {warehouseCount}");               
                if (warehouseCount > 0)
                {
                    var sampleWarehouse = await warehouseQueryable.FirstOrDefaultAsync();
                    Console.WriteLine($"   样本仓库: {sampleWarehouse?.Warehousename} (ID: {sampleWarehouse?.Id})");
                }                
                // 测试货品表
                Console.WriteLine("4. 测试货品表 (Dm_Item)...");
                var itemQueryable = await _itemRepository.GetQueryableAsync();
                var itemCount = await itemQueryable.CountAsync();
                Console.WriteLine($"   货品表记录数: {itemCount}");               
                if (itemCount > 0)
                {
                    var sampleItem = await itemQueryable.FirstOrDefaultAsync();
                    Console.WriteLine($"   样本货品: {sampleItem?.Itemname} (ID: {sampleItem?.Id})");
                }               
                Console.WriteLine("=== 数据库连接测试完成 ===");               
                return $"单位: {unitCount}, 货品类型: {itemTypeCount}, 仓库: {warehouseCount}, 货品: {itemCount}";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库连接测试异常: {ex.Message}");
                Console.WriteLine($"异常类型: {ex.GetType().Name}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return $"异常: {ex.Message}";
            }
        }
        /// <summary>
        /// 添加货品
        /// </summary>
        public async Task<GoodsOutput> AddGoodsAsync(AddGoodsInput input)
        {
            try
            {
                // 检查货品编码是否已存在
                var existingItem = await _itemRepository.GetQueryableAsync();
                var isExists = await existingItem.AnyAsync(x => x.Itemid == input.ItemId);               
                if (isExists)
                {
                    throw new Exception($"货品编码 {input.ItemId} 已存在");
                }
                // 创建新的货品实体
                var goods = new Dm_Item
                {
                    Itemid = input.ItemId,
                    Itemname = input.ItemName,
                    Itemtypeid = input.ItemTypeId,
                    Itemspec = input.ItemSpec,
                    Unitid = input.UnitId,
                    Entid = input.EntId,
                    Clientid = input.ClientId,
                    Purchaseprice = input.PurchasePrice,
                    Outboundprice = input.OutboundPrice,
                    Satus = input.Status
                };
                // 保存到数据库
                var savedGoods = await _itemRepository.InsertAsync(goods);
                // 转换为输出DTO
                var goodsOutput = ObjectMapper.Map<Dm_Item, GoodsOutput>(savedGoods);
                // 获取关联数据
                if (!string.IsNullOrEmpty(savedGoods.Itemtypeid))
                {
                    try
                    {
                        var itemTypeQueryable = await _itemTypeRepository.GetQueryableAsync();
                        var itemType = await itemTypeQueryable
                            .Where(x => x.Itemtypeid == savedGoods.Itemtypeid)
                            .FirstOrDefaultAsync();
                        goodsOutput.ItemTypeName = itemType?.Itemtypename;
                    }
                    catch
                    {
                        goodsOutput.ItemTypeName = "未知类型";
                    }
                }
                if (!string.IsNullOrEmpty(savedGoods.Unitid))
                {
                    try
                    {
                        var unitQueryable = await _unitRepository.GetQueryableAsync();
                        var unit = await unitQueryable
                            .Where(x => x.Unitid == savedGoods.Unitid)
                            .FirstOrDefaultAsync();
                        goodsOutput.UnitName = unit?.Unitname;
                    }
                    catch
                    {
                        goodsOutput.UnitName = "未知单位";
                    }
                }
                // 设置模拟数据
                goodsOutput.WarehouseName = "主仓库";
                goodsOutput.LocationName = "A区-01-01";
                goodsOutput.Barcode = $"BAR{savedGoods.Itemid}";
                goodsOutput.CurrentInventory = 0; // 新货品初始库存为0
                goodsOutput.InventoryAmount = 0;
                goodsOutput.InboundQuantity = 0;
                goodsOutput.OutboundQuantity = 0;
                return goodsOutput;
            }
            catch (Exception ex)
            {
                throw new Exception($"添加货品失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 修改货品
        /// </summary>
        public async Task<GoodsOutput> UpdateGoodsAsync(UpdateGoodsInput input)
        {
            try
            {
                // 获取现有货品
                var existingGoods = await _itemRepository.GetAsync(input.Id);
                // 检查货品编码是否被其他货品使用
                if (existingGoods.Itemid != input.ItemId)
                {
                    var queryable = await _itemRepository.GetQueryableAsync();
                    var isExists = await queryable.AnyAsync(x => x.Itemid == input.ItemId && x.Id != input.Id);
                    
                    if (isExists)
                    {
                        throw new Exception($"货品编码 {input.ItemId} 已存在");
                    }
                }
                // 更新货品信息
                existingGoods.Itemid = input.ItemId;
                existingGoods.Itemname = input.ItemName;
                existingGoods.Itemtypeid = input.ItemTypeId;
                existingGoods.Itemspec = input.ItemSpec;
                existingGoods.Unitid = input.UnitId;
                existingGoods.Entid = input.EntId;
                existingGoods.Clientid = input.ClientId;
                existingGoods.Purchaseprice = input.PurchasePrice;
                existingGoods.Outboundprice = input.OutboundPrice;
                existingGoods.Satus = input.Status;
                // 保存到数据库
                var updatedGoods = await _itemRepository.UpdateAsync(existingGoods);
                // 转换为输出DTO
                var goodsOutput = ObjectMapper.Map<Dm_Item, GoodsOutput>(updatedGoods);
                // 获取关联数据
                if (!string.IsNullOrEmpty(updatedGoods.Itemtypeid))
                {
                    try
                    {
                        var itemTypeQueryable = await _itemTypeRepository.GetQueryableAsync();
                        var itemType = await itemTypeQueryable
                            .Where(x => x.Itemtypeid == updatedGoods.Itemtypeid)
                            .FirstOrDefaultAsync();
                        goodsOutput.ItemTypeName = itemType?.Itemtypename;
                    }
                    catch
                    {
                        goodsOutput.ItemTypeName = "未知类型";
                    }
                }
                if (!string.IsNullOrEmpty(updatedGoods.Unitid))
                {
                    try
                    {
                        var unitQueryable = await _unitRepository.GetQueryableAsync();
                        var unit = await unitQueryable
                            .Where(x => x.Unitid == updatedGoods.Unitid)
                            .FirstOrDefaultAsync();
                        goodsOutput.UnitName = unit?.Unitname;
                    }
                    catch
                    {
                        goodsOutput.UnitName = "未知单位";
                    }
                }
                // 设置模拟数据
                goodsOutput.WarehouseName = "主仓库";
                goodsOutput.LocationName = "A区-01-01";
                goodsOutput.Barcode = $"BAR{updatedGoods.Itemid}";
                goodsOutput.CurrentInventory = 100; // 模拟库存
                goodsOutput.InventoryAmount = goodsOutput.CurrentInventory * updatedGoods.Purchaseprice;
                goodsOutput.InboundQuantity = 150;
                goodsOutput.OutboundQuantity = 50;
                return goodsOutput;
            }
            catch (Exception ex)
            {
                throw new Exception($"修改货品失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 删除货品
        /// </summary>
        public async Task<bool> DeleteGoodsAsync(Guid id)
        {
            try
            {
                // 检查货品是否存在
                var existingGoods = await _itemRepository.GetAsync(id);
                // 删除货品
                await _itemRepository.DeleteAsync(existingGoods);             
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception($"删除货品失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 根据ID获取货品详情
        /// </summary>
        public async Task<GoodsOutput> GetGoodsByIdAsync(Guid id)
        {
            try
            {
                // 获取货品
                var goods = await _itemRepository.GetAsync(id);
                // 转换为输出DTO
                var goodsOutput = ObjectMapper.Map<Dm_Item, GoodsOutput>(goods);
                // 获取关联数据
                if (!string.IsNullOrEmpty(goods.Itemtypeid))
                {
                    try
                    {
                        var itemTypeQueryable = await _itemTypeRepository.GetQueryableAsync();
                        var itemType = await itemTypeQueryable
                            .Where(x => x.Itemtypeid == goods.Itemtypeid)
                            .FirstOrDefaultAsync();
                        goodsOutput.ItemTypeName = itemType?.Itemtypename;
                    }
                    catch
                    {
                        goodsOutput.ItemTypeName = "未知类型";
                    }
                }
                if (!string.IsNullOrEmpty(goods.Unitid))
                {
                    try
                    {
                        var unitQueryable = await _unitRepository.GetQueryableAsync();
                        var unit = await unitQueryable
                            .Where(x => x.Unitid == goods.Unitid)
                            .FirstOrDefaultAsync();
                        goodsOutput.UnitName = unit?.Unitname;
                    }
                    catch
                    {
                        goodsOutput.UnitName = "未知单位";
                    }
                }
                // 设置模拟数据
                goodsOutput.WarehouseName = "主仓库";
                goodsOutput.LocationName = "A区-01-01";
                goodsOutput.Barcode = $"BAR{goods.Itemid}";
                goodsOutput.CurrentInventory = 100;
                goodsOutput.InventoryAmount = goodsOutput.CurrentInventory * goods.Purchaseprice;
                goodsOutput.InboundQuantity = 150;
                goodsOutput.OutboundQuantity = 50;

                return goodsOutput;
            }
            catch (Exception ex)
            {
                throw new Exception($"获取货品详情失败: {ex.Message}");
            }
        }

        public async Task<GoodsInventoryDetailOutput> GetGoodsInventoryDetailAsync(Guid goodsId)
        {
            try
            {
                var item = await _itemRepository.GetAsync(goodsId);
                if (item == null)
                {
                    throw new UserFriendlyException("货品不存在");
                }

                var result = new GoodsInventoryDetailOutput();

                // 获取货品类型和单位信息
                string itemTypeName = "未知类型";
                string unitName = "未知单位";


                if (!string.IsNullOrEmpty(item.Itemtypeid))
                {
                    try
                    {
                        var itemTypeQueryable = await _itemTypeRepository.GetQueryableAsync();
                        var itemType = await itemTypeQueryable.FirstOrDefaultAsync(x => x.Itemtypeid == item.Itemtypeid);
                        
                        itemTypeName = itemType?.Itemtypename ?? "未知类型";
                    }
                    catch { 

                    }
                }

                if (!string.IsNullOrEmpty(item.Unitid))
                {
                    try
                    {
                        var unitQueryable = await _unitRepository.GetQueryableAsync();
                        var unit = await unitQueryable.FirstOrDefaultAsync(x => x.Unitid == item.Unitid);
                        unitName = unit?.Unitname ?? "未知单位";
                    }
                    catch { 
                    }
                }

                // 构建货品详情信息
                result.GoodsInfo = new GoodsDetailOutput
                {
                    Id = item.Id,
                    ItemId = item.Itemid,
                    ItemName = item.Itemname,
                    ItemTypeName = itemTypeName,
                    ItemSpec = item.Itemspec,
                    UnitName = unitName,
                    CurrentInventory = 500,
                    AvailableInventory = 400,
                    PendingOutbound = 50,
                    PendingInbound = 50
                };

                // 获取仓库和库位信息，构建库存明细
                try
                {
                    var warehouseQueryable = await _warehouseRepository.GetQueryableAsync();
                    var locationQueryable = await _locationRepository.GetQueryableAsync();

                    var warehouses = await warehouseQueryable.Where(x => !string.IsNullOrEmpty(x.Warehouseid)).ToListAsync();
                    var locations = await locationQueryable.Where(x => !string.IsNullOrEmpty(x.Librarylocationid)).ToListAsync();

                    int serialNo = 1;
                    foreach (var warehouse in warehouses.Take(5)) // 限制显示前5个仓库
                    {
                        foreach (var location in locations.Take(2)) // 每个仓库显示2个库位
                        {
                            result.InventoryDetails.Add(new InventoryDetailOutput
                            {
                                SerialNo = serialNo++,
                                WarehouseName = warehouse.Warehousename,
                                LocationName = location.Librarylocationname,
                                CurrentInventory = 500,
                                AvailableInventory = 100,
                                PendingInbound = 20,
                                PendingOutbound = 20
                            });
                        }
                    }
                }
                catch
                {
                    // 如果获取仓库库位信息失败，使用模拟数据
                    for (int i = 1; i <= 10; i++)
                    {
                        result.InventoryDetails.Add(new InventoryDetailOutput
                        {
                            SerialNo = i,
                            WarehouseName = "仓库一",
                            LocationName = "仓位一",
                            CurrentInventory = 500,
                            AvailableInventory = 100,
                            PendingInbound = 20,
                            PendingOutbound = 20
                        });
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"获取货品库存详情失败: {ex.Message}");
            }
        }

        public async Task<GoodsInventoryDetailOutput> GetGoodsInventoryDetailByItemIdAsync(string itemId)
        {
            try
            {
                var itemQueryable = await _itemRepository.GetQueryableAsync();
                var item = await itemQueryable.FirstOrDefaultAsync(x => x.Itemid == itemId);
                if (item == null)
                {
                    throw new UserFriendlyException("货品不存在");
                }
                return await GetGoodsInventoryDetailAsync(item.Id);
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"获取货品库存详情失败: {ex.Message}");
            }
        }

        public async Task<byte[]> ExportGoodsInventoryDetailAsync(Guid goodsId)
        {
            try
            {
                var detail = await GetGoodsInventoryDetailAsync(goodsId);
                
                // 这里实现导出逻辑，可以使用EPPlus或其他库
                // 暂时返回空数组，实际项目中需要实现具体的导出逻辑
                return new byte[0];
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"导出货品库存明细失败: {ex.Message}");
            }
        }
    }
} 